package test0ne.设计模式.备忘录;

import java.util.ArrayList;
import java.util.List;

public class Editor {
    private Doc doc;
    private List<History> historieRecord ;
    private int index = -1;  //记录当前位置

    public Editor(Doc doc) {
        System.out.printf("<<<打开文档"+doc.getName());
        this.doc = doc;
        historieRecord = new ArrayList<History>();
        bachup();
        show();
    }

    public void append(String body) {
        System.out.println("<<<插入操作");
        doc.setBody(doc.getBody()+body);
        bachup();
        show();
    }

    public void save() {
        System.out.println("<<<存盘操作");
    }

    public void delete() {
        System.out.println("<<<删除操作");
        doc.setBody("");
        bachup();
        show();
    }

    private void show() {
        System.out.println(doc.getBody());
        System.out.println("文章结束>>>\n");
    }

    public void bachup() {
        historieRecord.add(doc.createHistory());
        index++;
    }

    public void undo() {
        System.out.println(">>>撤销操作");
        if(index == 0) {
            return;
        }
        index--;
        doc.restoreHistory(historieRecord.get(index));
        show();
    }
}
